<template>
  <div class="shoppingCart">
    <div
      class="nav acea-row row-between-wrapper"
      style="background:white;border-radius:0.08rem;height:0.8rem;"
      v-if="cartList.valid.length > 0"
    >
      <div>
        购物数量 <span class="num font-color-red">{{ count }}</span>
      </div>
      <div class="administrate acea-row row-center-wrapper" @click="manage">
        {{ footerswitch ? "完成" : "管理" }}
      </div>
    </div>
    <div v-if="cartList.valid.length > 0 || cartList.invalid.length > 0">
      <div class="list">
        <div
          class="item acea-row row-between-wrapper"
          v-for="(item, index) in cartList.valid"
          :key="index"
        >
          <div class="card-title" @click="toGoodsList(item.mer_id)">
            <img class="shopImg" src="@assets/images/shopgery.png" alt="" />
            <span>{{ item.merchant_name }}</span>
            <img class="toShopImg" src="@assets/images/to-shop.png" alt="" />
          </div>
          <div class="coupon_info">
            <span v-for="(plat, index) in item.plat_coupon" :key="index">
              平台通用卷
              <i>满{{ plat.use_min_price }}减{{ plat.coupon_price }}</i>
            </span>
          </div>
          <div class="select-btn">
            <div class="checkbox-wrapper">
              <label class="well-check">
                <input
                  type="checkbox"
                  name=""
                  value=""
                  :checked="item.checked"
                  @click="switchSelect(index)"
                />
                <i class="icon icon1"></i>
              </label>
            </div>
          </div>
          <div class="picTxt acea-row row-between-wrapper">
            <div
              class="pictrue"
              style="position: relative;"
              @click="
                $router.push({
                  path: '/detail/' + item.product_id + '?mer_id=' + item.mer_id
                })
              "
            >
              <img
                v-show="item.is_free == '1'"
                style="position:absolute;width:.9rem;height:0.38rem;right:0;top:0;border-radius: 0"
                src="@assets/images/freeBay.png"
                alt=""
              />
              <img
                v-if="item.is_seckill == '1'"
                style="position:absolute;width:1.16rem;height:0.38rem;right:0;top:0;border-radius: 0"
                src="@assets/images/seckill.png"
                alt=""
              />
              <img :src="item.seckill.image" v-if="item.is_seckill == '1'" />
              <img
                :src="item.productInfo.attrInfo.image"
                v-else-if="item.productInfo.attrInfo && item.is_seckill == '0'"
              />
              <img :src="item.productInfo.image" v-else />
            </div>
            <div class="text">
              <div class="line1" v-if="item.is_seckill == '1'">
                <span
                  style="display: inline-block;margin-top: 0.01rem;padding: 0 0.06rem;border-radius: 0.04rem;margin-right: 0.08rem;height: auto;border: 0.02rem solid rgba(255,35,35,0.38);font-size: 0.24rem;font-weight: 400;color: rgba(255,35,35,0.78);line-height: 1;"
                  >{{ item.seckill.countTime }}</span
                >{{ item.seckill.title }}
              </div>
              <div class="line1" v-if="item.is_seckill == '0'">
                {{ item.productInfo.store_name }}
              </div>
              <div
                class="infor"
                v-if="item.productInfo.attrInfo"
                style="overflow: hidden; white-space: nowrap; text-overflow: ellipsis;"
              >
                属性：{{ item.productInfo.attrInfo.suk }}
              </div>
              <div class="money" v-if="item.is_free == '1'">￥0.00</div>
              <div
                class="money"
                v-if="item.is_seckill == '0' && item.is_free == '0'"
              >
                ￥{{ item.truePrice }}
              </div>
              <div class="money" v-if="item.is_seckill == '1'">
                ￥{{ item.seckill.price }}
              </div>
            </div>
            <div class="carnum acea-row row-center-wrapper">
              <div
                class="reduce"
                :class="cartList.valid[index].cart_num <= 1 ? 'on' : ''"
                v-show="item.is_limit_buy == '0' && item.is_free == '0'"
                @click.prevent="reduce(index, item.productInfo.stock)"
                style="background:rgba(251,251,251,1);"
              >
                -
              </div>
              <div class="num">
                <input
                  type="tel"
                  v-model="item.cart_num"
                  v-show="item.is_limit_buy == '0' && item.is_free == '0'"
                  class="ipt_num"
                  @input.prevent="specifiName(index, item.productInfo.stock)"
                  @blur.prevent="blurName(index, item.productInfo.stock)"
                />
                <input
                  type="tel"
                  v-model="item.cart_num"
                  v-show="item.is_limit_buy == '1' || item.is_free == '1'"
                  readonly="readonly"
                  class="ipt_num"
                  @input.prevent="specifiName(index, item.productInfo.stock)"
                  @blur.prevent="blurName(index, item.productInfo.stock)"
                />
              </div>
              <div
                class="plus"
                v-if="cartList.valid[index].attrInfo"
                v-show="item.is_limit_buy == '0' && item.is_free == '0'"
                :class="
                  cartList.valid[index].cart_num >=
                  cartList.valid[index].attrInfo.stock
                    ? 'on'
                    : ''
                "
                @click.prevent="plus(index, item.productInfo.stock)"
              >
                +
              </div>
              <div
                class="plus"
                v-show="item.is_limit_buy == '0' && item.is_free == '0'"
                v-else
                :class="
                  cartList.valid[index].cart_num >= cartList.valid[index].stock
                    ? 'on'
                    : ''
                "
                @click.prevent="plus(index, item.productInfo.stock)"
              >
                +
              </div>
            </div>
          </div>
          <div class="coupon_info">
            <span v-for="(product, index) in item.product_coupon" :key="index">
              满减劵
              <i>满{{ product.use_min_price }}减{{ product.coupon_price }}</i>
              仅限指定商品
            </span>
          </div>
        </div>
      </div>
      <div class="invalidGoods list" v-if="cartList.invalid.length > 0">
        <div class="goodsNav acea-row row-between-wrapper">
          <div>
            失效商品
          </div>
          <div class="del" @click="delInvalidGoods">
            <img
              src="@assets/images/delete.png"
              alt=""
              srcset=""
              style="width: 0.38rem;vertical-align: bottom;"
            />
            清空失效宝贝
          </div>
        </div>
        <div class="goodsList" style="opacity: 0.5;">
          <div
            class="item acea-row row-between-wrapper"
            v-for="(item, index) in cartList.invalid"
            :key="index"
          >
            <div class="select-btn">
              <div class="checkbox-wrapper">
                <div class="invalid acea-row row-center-wrapper">失效</div>
              </div>
            </div>
            <div
              class="picTxt acea-row row-between-wrapper"
              style="width:6.07rem;"
            >
              <!-- @click="$router.push({ path: '/detail/' + item.product_id })"  -->
              <div class="pictrue" @click="tip()">
                <img v-if="item.productInfo" :src="item.productInfo.image" />
                <img :src="item.image" v-else />
              </div>
              <div class="text" style="width: 3.9rem;">
                <div class="line1" v-if="item.productInfo">
                  {{ item.productInfo.store_name }}
                </div>
                <div class="line1" v-else>{{ item.store_name }}</div>
                <!-- v-if="item.productInfo.attrInfo" -->
                <div
                  class="infor"
                  style="overflow: hidden; white-space: nowrap; text-overflow: ellipsis;"
                >
                  <!-- 属性：{{ item.productInfo.attrInfo.suk }} -->
                  该商品已下架
                </div>
                <!-- <div class="money">￥{{ item.truePrice }}</div> -->
              </div>
              <!-- <div class="carnum acea-row row-center-wrapper">
                <div
                  class="reduce"
                  :class="cartList.valid[index].cart_num <= 1 ? 'on' : ''"
                  @click.prevent="reduce(index,item.productInfo.stock)"
                  style="background:rgba(251,251,251,1);"
                >
                  -
                </div>
                <div class="num">
                  <input
                    type="number"
                    v-model="item.cart_num"
                    class="ipt_num"
                    @input.prevent="specifiName(index,item.productInfo.stock)"
                    @blur.prevent="blurName(index,item.productInfo.stock)"
                  />
                </div>
                <div
                  class="plus"
                  v-if="cartList.valid[index].attrInfo"
                  :class="
                    cartList.valid[index].cart_num >=
                    cartList.valid[index].attrInfo.stock
                      ? 'on'
                      : ''
                  "
                  @click.prevent="plus(index,item.productInfo.stock)"
                >
                  +
                </div>
                <div
                  class="plus"
                  v-else
                  :class="
                    cartList.valid[index].cart_num >= cartList.valid[index].stock
                      ? 'on'
                      : ''
                  "
                  @click.prevent="plus(index,item.productInfo.stock)"
                >
                  +
                </div>
              </div> -->
            </div>
          </div>
          <!-- <router-link
            :to="{ path: '/detail/' + item.product_id }"
            class="item acea-row row-between-wrapper"
            v-for="(item, index) in cartList.invalid"
            :key="index"
          >
            <div class="invalid acea-row row-center-wrapper">失效</div>
            <div class="pictrue">
              <img
                :src="item.productInfo.attrInfo.image"
                v-if="item.productInfo.attrInfo"
              />
              <img :src="item.productInfo.image" v-else />
            </div>
            <div class="text acea-row row-column-between">
              <div class="line1">{{ item.productInfo.store_name }}</div>
              <div class="infor line1" v-if="item.productInfo.attrInfo">
                属性：{{ item.productInfo.attrInfo.suk }}
              </div>
              <div class="acea-row row-between-wrapper">
                <div class="end">该商品已下架</div>
              </div>
            </div>
          </router-link> -->
        </div>
      </div>
    </div>
    <!--购物车暂无商品-->
    <div
      class="noCart"
      v-if="
        cartList.valid.length === 0 &&
          cartList.invalid.length === 0 &&
          ishave == true
      "
    >
      <div class="pictrue">
        <img src="@assets/images/noCart.png" />
      </div>
      <p class="txt">暂无商品,去添加点什么吧</p>
      <!-- <Recommend></Recommend> -->
    </div>
    <div style="height:2.1rem"></div>
    <div
      class="footer acea-row row-between-wrapper"
      v-if="cartList.valid.length > 0"
    >
      <div class="left_info">
        <div class="select-btn">
          <div class="checkbox-wrapper">
            <label class="well-check">
              <input
                type="checkbox"
                name=""
                value=""
                :checked="isAllSelect && cartCount > 0"
                @click="allChecked"
              />
              <i class="icon"></i>
              <span class="checkAll">全选 </span>
            </label>
          </div>
        </div>
        <div class="money_and_couponinfo">
          <div>
            <span class="font-color-notRed">合计：</span>
            <span class="font-color-red"
              >￥{{ couponDetail.orderTotalPrice }}</span
            >
          </div>
          <div
            v-show="Number(couponDetail.total_reduce) != 0"
            class="couponinfo"
            @click="(couponWindow = !couponWindow), (posters = !posters)"
          >
            共减<span>￥{{ couponDetail.total_reduce }}</span
            >优惠明细
            <img
              class="icon"
              :class="couponWindow ? 'on' : ''"
              src="@assets/images/coupon/roow.png"
              alt=""
            />
          </div>
        </div>
      </div>
      <div class="money acea-row row-middle" v-show="footerswitch === false">
        <div class="placeOrder bg-color-red" @click="placeOrder">
          结算({{ cartCount }})
        </div>
      </div>
      <div class="button acea-row row-middle" v-show="footerswitch === true">
        <!-- <div class="bnt cart-color" @click="collectAll">收藏</div> -->
        <div class="bnt" @click="suredelgoods">删除</div>
      </div>
    </div>
    <div class="yd-dialog-black-mask" v-show="isdelete == true">
      <div class="yd-confirm">
        <div class="yd-confirm-hd">
          <strong class="yd-confirm-title">提示</strong>
        </div>
        <div class="yd-confirm-bd">{{ delMsg }}</div>
        <div class="yd-confirm-ft">
          <a
            href="javascript:;"
            class="yd-confirm-btn default"
            @click="nodelgoods"
            >{{ notSureMsg }}</a
          >
          <a
            href="javascript:;"
            class="yd-confirm-btn primary"
            @click="delgoods"
            >{{ suredelMsg }}</a
          >
        </div>
      </div>
    </div>
    <!-- 优惠明细弹窗 -->
    <div class="coupon-list-window" :class="couponWindow === true ? 'on' : ''">
      <div class="new_title">
        <p>优惠明细</p>
        <p>实际下单金额以下单页为准</p>
      </div>
      <div class="coupon-list">
        <p>
          <span>商品总价</span>
          <span>￥{{ couponDetail.total_price }}</span>
        </p>
        <p>
          <span>平台优惠劵</span>
          <span class="red">-￥{{ couponDetail.coupon_price }}</span>
        </p>
        <p>
          <span>首单立减</span>
          <span class="red">-￥{{ couponDetail.deduction_price }}</span>
        </p>
        <p>
          <span>合计</span>
          <span>￥{{ couponDetail.orderTotalPrice }}</span>
        </p>
      </div>
    </div>
    <div
      class="mask"
      @touchmove.prevent
      @click="(couponWindow = false), (posters = false)"
      v-show="posters"
    ></div>
  </div>
</template>
<script>
// import Recommend from "@components/Recommend";
import {
  getCartList,
  postCartDel,
  changeCartNum,
  getCartCount
} from "@api/store";
import { postCollectAll } from "@api/user";
import { mul, add } from "@utils/bc";
import cookie from "@utils/store/cookie";
import base from "@common/base";
import { clearAuthStatus } from "@libs/wechat";
import shareMsg from "../../assets/js/common/shareConfig.js";
import debounce from "lodash.debounce";
import dayjs from "dayjs";
import { constants } from "fs";
import { isWeixin } from "@utils";
const CHECKED_IDS = "cart_checked";
import {
  postOrderConfirm,
  postOrderComputed,
  createOrder,
  getOpenId
} from "@api/order";

export default {
  name: "ShoppingCart",
  components: {
    // Recommend
  },
  props: {},
  data: function() {
    return {
      couponDetail: {
        // 优惠详细信息
        total_reduce: "0.00",
        total_price: "0.00",
        coupon_price: "0.00",
        deduction_price: "0.00",
        orderTotalPrice: "0.00"
      },
      couponWindow: false,
      cartList: { invalid: [], valid: [] },
      isAllSelect: false,
      cartCount: 0,
      countmoney: 0,
      goodsHidden: true,
      footerswitch: false,
      count: 0,
      checkedIds: [],
      loaded: false,
      index_num: 0,
      from1: "",
      isdelete: false,
      delMsg: "",
      suredelMsg: "",
      notSureMsg: "",
      delType: "",
      ishave: false,
      timer: "",
      countTimetimer: "",
      listLength: 0
    };
  },
  watch: {
    $route(n) {
      if (n.name === "ShoppingCart") {
        this.carnum();
        this.countMoney();
        this.getCartList();
        this.gainCount();
        this.goodsHidden = true;
        this.footerswitch = false;
      }
    },
    checkedIds: {
      deep: true,
      handler(ids) {
        if (ids.length == 0) {
          for (const key in this.couponDetail) {
            this.couponDetail[key] = "0.00";
          }
        }
      }
    }
  },
  // beforeCreate(){

  // },
  created() {},
  mounted: function() {
    let that = this;
    if (this.$route.query.isToken) {
      this.$store.commit(
        "LOGIN",
        this.$route.query.isToken
        // dayjs(expires_time) - newTime
      );
      cookie.set("OID", this.$route.query.oId);
    }
    let isFromApp = this.$route.query.from1;
    if (isFromApp == undefined) {
      isFromApp = "h5";
    }
    this.from1 = isFromApp;
    if (this.from1 == "app") {
      if (cookie.get("from1") == "" || cookie.get("from1") == undefined) {
        cookie.set("from1", "app");
      }
      this.getParameter();
      this.isNo();
      window["onWebResponse"] = str => {
        that.onWebResponse(str);
      };

      that.timer = setInterval(function() {
        shareMsg.shareConfig("app", "0", "0", "", "", "", "", "", "0");
      }, 500);
    } else if (this.from1 == "wxapp") {
      that.carnum();
      that.countMoney();
      that.getCartList();
      that.gainCount();
    } else {
      that.carnum();
      that.countMoney();
      that.getCartList();
      that.gainCount();
    }
    var u = navigator.userAgent,
      app = navigator.appVersion;
    var isAndroid = u.indexOf("Android") > -1 || u.indexOf("Linux") > -1; //g
    var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端

    this.componentDidMount();
  },
  methods: {
    // 获取订单key 用于计算金额
    getCartInfo() {
      const cartIdArr =
        this.cartList.valid
          .filter(item => item.checked == true)
          .map(item => item.id) || [];
      if (cartIdArr.length == 0) return;
      const params = {
        cartIdArr,
        type: 1
      };
      postOrderConfirm(params)
        .then(res => {
          this.computedPrice(res.data.orderKey);
        })
        .catch(res => {
          this.$dialog.error(res.msg);
        });
    },
    // 计算金额
    computedPrice(order_key) {
      postOrderComputed(order_key, {
        addressId: "",
        useIntegral: 0,
        couponId: 0,
        shipping_type: 1,
        payType: "weChatPay",
        type: 1
      })
        .then(res => {
          this.couponDetail = res.data.result;
        })
        .catch(res => {
          this.$dialog.error(res.msg);
        });
    },
    getElementOffsetTop(el) {
      let top = el.offsetTop;
      let cur = el.offsetParent;
      while (cur != null) {
        top += cur.offsetTop;
        cur = cur.offsetParent;
      }
      return top;
    },

    componentDidMount() {
      const u = navigator.userAgent;
      const isAndroid = u.indexOf("Android") > -1 || u.indexOf("Linux") > -1; //android终端
      // alert('android'+isAndroid)
      // if(isAndroid && this.from1 != 'app'){ // android统一处理，不影响ios的自身处理
      const body = document.getElementsByTagName("body")[0]; // 兼容获取body
      const regDom = document.querySelector(".shoppingCart"); // 获取页面根元素
      const content = document.querySelector(".shoppingCart"); // 表单内容部分

      // const scrollHeight = body.scrollHeight // 网页文档高
      // const scrollTop = body.scrollTop// 卷上去的高

      const clientHeight = body.clientHeight; //可见高
      const fixHeight = clientHeight / 3; // 定位高，弹出键盘时input距浏览器上部的距离，自己定义合适的

      // 符合需弹出键盘的元素query
      const queryStr =
        'input[type="text"], input[type="tel"], input[type="password"], textarea';
      const inputs = content.querySelectorAll(queryStr);

      // console.log(inputs)

      const offsetTopArr = Array.prototype.map.call(inputs, item => {
        return this.getElementOffsetTop(item); // offsetTop只能获取到顶部距它的offsetParent的距离，需此方法获取到元素距顶部的距离
      });

      inputs.forEach((item, i) => {
        item.addEventListener("focus", () => {
          // 改变top上移页面
          regDom.style.top = "-" + (offsetTopArr[i] - fixHeight) + "px";
        });

        item.addEventListener("blur", () => {
          // 恢复top
          regDom.style.top = 0;
        });
      });
      // }
    },
    //声音禁掉
    isNo: function() {
      var u = navigator.userAgent,
        app = navigator.appVersion;
      var isAndroid = u.indexOf("Android") > -1 || u.indexOf("Linux") > -1; //g
      var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
      const win = window;
      var obj = {
        action: "onClickPlay",
        content: {}
      };
      if (isAndroid) {
        App.onAppResponse(JSON.stringify(obj));
      }
      if (isIOS) {
        win.webkit.messageHandlers.onAppResponse.postMessage(
          JSON.stringify(obj)
        );
      }
    },
    toGoodsList: function(id) {
      if (this.from1 == "app") {
        this.$router.push({ path: "/goods_list/" + id + "?from1=app" });
      } else if (this.from1 == "wxapp") {
        this.$router.push({ path: "/goods_list/" + id + "?from1=wxapp" });
      } else {
        this.$router.push({ path: "/goods_list/" + id });
      }
    },
    getParameter: function() {
      var self = this;
      var u = navigator.userAgent,
        app = navigator.appVersion;
      var isAndroid = u.indexOf("Android") > -1 || u.indexOf("Linux") > -1; //g
      var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
      const win = window;
      var obj = {
        action: "getParameter",
        content: {
          method: "setUserInfo",
          Parameter: {}
        }
      };
      if (isAndroid) {
        App.onAppResponse(JSON.stringify(obj));
      }
      if (isIOS) {
        win.webkit.messageHandlers.onAppResponse.postMessage(
          JSON.stringify(obj)
        );
      }
    },
    // 嵌入app获取支付状态
    onWebResponse: function(str) {
      // alert(123);
      var obj = JSON.parse(str);
      var action = obj.action;
      var self = this;
      var content = obj.content;
      if (action == "setUserInfo") {
        let did = content.did;
        let isToken = content.ds_token;
        let expires_time = content.ds_expires_time;
        let isSalt = content.salt;
        if (isToken == "") {
          this.$store.commit(
            "LOGIN",
            isToken
            // dayjs(expires_time) - newTime
          );
        } else {
          this.$store.commit(
            "LOGIN",
            isToken
            // dayjs(expires_time) - newTime
          );
        }
        // setTimeout(function() {
        this.carnum();
        this.countMoney();
        this.getCartList();
        this.gainCount();
        // }, 1000);
      }
    },
    getCartList: function() {
      let that = this;
      getCartList().then(res => {
        that.cartList = res.data;
        this.ishave = true;
        let checkedIds = [];
        that.$set(that.cartList.valid, "checked", false);
        if (!Array.isArray(checkedIds)) checkedIds = [];
        this.cartList.valid.forEach(cart => {
          if (checkedIds.length) {
            if (checkedIds.indexOf(cart.id) !== -1) cart.checked = true;
            else cart.checked = false;
          }
        });

        if (checkedIds.length) {
          that.checkedIds = checkedIds;
        }
        that.isAllSelect =
          that.checkedIds.length === this.cartList.valid.length;
        this.countTimeFunction();
        that.carnum();
        that.countMoney();
        this.loaded = true;
        this.getCartInfo();
      });
    },
    countTimeFunction() {
      var self = this;
      if (self.countTimetimer != "") {
        clearInterval(self.countTimetimer);
      }
      self.countTimetimer = setInterval(function() {
        self.listLength = 0;
        self.cartList.valid.forEach((value, index) => {
          if (value.is_seckill == "1") {
            var timeDom = "";
            var date = new Date();
            var now = parseInt(date.getTime() / 1000);
            var differTime = value.seckill.stop_time - now;
            console.log(differTime);
            // console.log(now);
            var h, m, s;
            if (differTime >= 0) {
              h = Math.floor(differTime / 60 / 60);
              m = Math.floor((differTime / 60) % 60);
              s = Math.floor(differTime % 60);
              h = h < 10 ? "0" + h : h;
              m = m < 10 ? "0" + m : m;
              s = s < 10 ? "0" + s : s;
              timeDom = h + ":" + m + ":" + s;
            } else {
              value.is_seckill = "0";
              timeDom = "";
            }
            self.$set(value.seckill, "countTime", timeDom);
          } else {
            self.listLength++;
          }
        });
        if (self.listLength == self.cartList.valid.length) {
          clearInterval(self.countTimetimer);
        }
      }, 1000);
    },
    tip() {
      this.$dialog.toast({ mes: "商品不存在或已下架" });
    },
    //删除商品；
    delgoods: function() {
      if (this.delType == "1") {
        let that = this,
          id = [],
          valid = [],
          list = that.cartList.valid;
        list.forEach(function(val) {
          if (val.checked === true) {
            id.push(val.id);
          }
        });
        if (id.length === 0) {
          that.$dialog.toast({ mes: "请选择产品" });
          return;
        }
        postCartDel(id).then(function() {
          list.forEach(function(val, i) {
            if (val.checked === false || val.checked === undefined)
              valid.push(list[i]);
          });
          that.$set(that.cartList, "valid", valid);
          that.carnum();
          that.countMoney();
          that.gainCount();
          that.isdelete = false;
        });
      } else if (this.delType == "2") {
        let that = this,
          id = [],
          list = that.cartList.invalid;
        list.forEach(function(val) {
          id.push(val.id);
        });
        postCartDel(id).then(function() {
          list.splice(0, list.length);
          that.gainCount();
          that.isdelete = false;
        });
      }
    },
    suredelgoods: function() {
      let that = this,
        id = [],
        valid = [],
        list = that.cartList.valid;
      list.forEach(function(val) {
        if (val.checked === true) {
          id.push(val.id);
        }
      });
      if (id.length === 0) {
        that.$dialog.toast({ mes: "请选择产品" });
        return;
      }
      this.delMsg = "是否删除所选商品?";
      this.notSureMsg = "取消";
      this.suredelMsg = "确定";
      this.delType = "1";
      this.isdelete = true;
    },
    nodelgoods: function() {
      this.isdelete = false;
    },
    // //获取数量
    gainCount: function() {
      let that = this;

      getCartCount().then(res => {
        that.count = res.data.count;
      });
    },
    //清除失效产品；
    delInvalidGoods: function() {
      this.delMsg = "是否清空失效商品?";
      this.notSureMsg = "我再想想";
      this.suredelMsg = "删除";
      this.delType = "2";
      this.isdelete = true;
    },
    //批量收藏;
    collectAll: function() {
      let that = this,
        data = { id: [], category: "" },
        list = that.cartList.valid;
      list.forEach(function(val) {
        if (val.checked === true) {
          data.id.push(val.product_id);
          data.category = val.type;
        }
      });
      if (data.id.length === 0) {
        that.$dialog.toast({ mes: "请选择产品" });
        return;
      }
      postCollectAll(data).then(function() {
        that.$dialog.toast({ mes: "收藏成功!" });
      });
    },
    //立即下单；
    placeOrder: function() {
      let that = this,
        list = that.cartList.valid,
        id = [];
      var mer_id = "";
      // if(cookie.get("mer_id") != undefined){
      //   cookie.remove("mer_id");
      // }
      list.forEach(function(val) {
        if (val.checked === true) {
          mer_id = val.mer_id;
          // cookie.set('mer_id',val.mer_id);
          id.push(val.id);
        }
      });
      if (id.length === 0) {
        that.$dialog.toast({ mes: "请选择产品" });
        return;
      }
      if (isWeixin()) {
        window.location.href =
          base.DsApiUrl() + "/order/submit/" + id + "?mer_id=" + mer_id;
      } else {
        this.$router.push({
          path: "/order/submit/" + id + "?mer_id=" + mer_id
        });
      }
    },
    manage: function() {
      let that = this;
      that.footerswitch = !that.footerswitch;
      // that.cartList.valid = that.cartList.valid;
    },
    goodsOpen: function() {
      let that = this;
      that.goodsHidden = !that.goodsHidden;
    },
    //加
    plus: function(index) {
      let that = this;
      let list = that.cartList.valid[index];
      list.cart_num++;
      if (list.cart_num >= list.trueStock) {
        that.$set(list, "cart_num", list.trueStock);
      }
      if (list.attrInfo) {
        if (list.cart_num >= list.attrInfo.stock) {
          that.$set(list, "cart_num", list.attrInfo.stock);
        }
      } else {
        if (list.cart_num >= list.stock) {
          that.$set(list, "cart_num", list.stock);
        }
      }
      that.carnum();
      that.countMoney();
      that.syncCartNum(list);
    },
    specifiName(index) {
      let list = this.cartList.valid[index];
      this.cartList.valid[index].cart_num = this.cartList.valid[
        index
      ].cart_num.replace(/[^\d]/g, "");
      // var r = /^\d+$/;
      // if (!r.test(parseFloat(this.cartList.valid[index].cart_num))) {
      //   this.cartList.valid[index].cart_num = "";
      // }
      if (
        this.cartList.valid[index].cart_num >
        this.cartList.valid[index].trueStock
      ) {
        this.cartList.valid[index].cart_num = this.cartList.valid[
          index
        ].trueStock;
        this.$dialog.toast({ mes: "购买数量不能大于库存" });
      }
      if (this.cartList.valid[index].cart_num === "0") {
        return (this.cartList.valid[index].cart_num = 1);
      }
      if (this.cartList.valid[index].cart_num > 65535) {
        this.cartList.valid[index].cart_num = 65535;
        return this.$dialog.toast({ mes: "购买数量最大值不能高于65535" });
      }
      if (list.attrInfo) {
        if (list.cart_num >= list.attrInfo.stock) {
          that.$set(list, "cart_num", list.attrInfo.stock);
        }
      } else {
        if (list.cart_num >= list.stock) {
          that.$set(list, "cart_num", list.stock);
        }
      }
      this.index_num = index;
      this.carnum();
      this.countMoney();
      this.syncCartNum(list);
    },
    blurName(index) {
      let list = this.cartList.valid[index];
      if (list.cart_num < 1) {
        this.$set(list, "cart_num", 1);
      }
      this.carnum();
      this.countMoney();
      this.syncCartNum(list);
    },
    //减
    reduce: function(index) {
      let that = this;
      let list = that.cartList.valid[index];
      list.cart_num--;
      if (list.cart_num < 1) {
        that.$set(list, "cart_num", 1);
      }
      that.carnum();
      that.countMoney();
      that.syncCartNum(list);
    },
    syncCartNum(cart) {
      const that = this;
      if (!cart.sync)
        cart.sync = debounce(() => {
          changeCartNum(cart.id, Math.max(cart.cart_num, 1) || 1)
            .then(res => {
              this.getCartInfo();
            })
            .catch(res => {
              that.getCartList();
              return that.$dialog.toast({ mes: res.msg });
            });
        }, 500);

      cart.sync();
    },
    //单选
    switchSelect: function(index) {
      let that = this,
        cart = that.cartList.valid[index],
        i = this.checkedIds.indexOf(cart.id);
      cart.checked = !cart.checked;
      if (i !== -1) this.checkedIds.splice(i, 1);
      if (cart.checked) {
        this.checkedIds.push(cart.id);
      }
      let len = that.cartList.valid.length;
      let selectnum = [];
      for (let i = 0; i < len; i++) {
        if (that.cartList.valid[i].checked === true) {
          selectnum.push(true);
        }
      }
      that.isAllSelect = selectnum.length === len;
      that.$set(that, "cartList", that.cartList);
      that.$set(that, "isAllSelect", that.isAllSelect);
      cookie.set(CHECKED_IDS, that.checkedIds);
      that.carnum();
      that.countMoney();
      if (this.checkedIds.length > 0) this.getCartInfo();
    },
    //全选
    allChecked: function() {
      let that = this;
      let selectAllStatus = that.isAllSelect;
      selectAllStatus = !selectAllStatus;
      let checkedIds = [];
      // for (let i = 0; i < array.length; i++) {
      //   array[i].checked = selectAllStatus;
      //   checked.push()
      // }
      that.cartList.valid.forEach(cart => {
        cart.checked = selectAllStatus;
        if (selectAllStatus) checkedIds.push(cart.id);
      });
      that.$set(that, "cartList", that.cartList);
      that.$set(that, "isAllSelect", selectAllStatus);
      this.checkedIds = checkedIds;
      cookie.set(CHECKED_IDS, checkedIds);
      that.carnum();
      that.countMoney();
      if (this.checkedIds.length > 0) this.getCartInfo(this.checkedIds);
    },
    //数量
    carnum: function() {
      let that = this;
      var carnum = 0;
      var array = that.cartList.valid;
      for (let i = 0; i < array.length; i++) {
        if (array[i].checked === true) {
          if (array[i].cart_num) carnum += parseInt(array[i].cart_num);
        }
      }
      that.$set(that, "cartCount", carnum);
    },
    //总共价钱；
    countMoney: function() {
      // let that = this;
      // let carmoney = 0;
      // let array = that.cartList.valid;
      // for (let i = 0; i < array.length; i++) {
      //   if (
      //     array[i].checked === true &&
      //     array[i].is_free != "1" &&
      //     array[i].is_seckill != "1"
      //   ) {
      //     carmoney = add(carmoney, mul(array[i].cart_num, array[i].truePrice));
      //   } else if (array[i].checked === true && array[i].is_seckill == "1") {
      //     carmoney = add(
      //       carmoney,
      //       mul(array[i].cart_num, array[i].seckill.price)
      //     );
      //   }
      // }
      // that.countmoney = carmoney;
    }
  },
  destroyed() {
    let self = this;
    clearInterval(self.timer);
  }
};
</script>
<style>
.yd-toast-none-icon {
  margin-bottom: 1rem;
}
</style>

<style lang="scss" scoped>
.shoppingCart .nav,
.shoppingCart .noCart {
  background: none;
}
.ipt_num {
  width: 100%;
  display: block;
  line-height: 0.44rem;
  text-align: center;
}
.noCart .pictrue img {
  width: 4rem;
  height: auto;
  margin: 0 auto;
  display: block;
}
.noCart .txt {
  font-size: 0.24rem;
  color: rgba(0, 0, 0, 0.4);
  text-align: center;
  letter-spacing: 0.01rem;
}
.coupon-list-window {
  .new_title {
    width: 100%;
    padding: 0.3rem 0 0.16rem 0;
    text-align: center;
    border-bottom: 1px solid rgba(0, 0, 0, 0.1);
    & p:first-child {
      font-size: 0.28rem;
      font-weight: bold;
      color: #000000;
      margin-bottom: 0.1rem;
    }
    & p:last-child {
      font-size: 0.2rem;
      font-weight: 400;
      color: rgba(0, 0, 0, 0.5);
    }
  }
  .coupon-list {
    p {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-top: 0.48rem;
      font-size: 0.28rem;
      font-weight: 400;
      color: #000000;
    }
    .red {
      color: #ff3c39;
    }
  }
}
</style>
